package fileDemo;

import java.io.*;
import java.util.Scanner;

public class Demo18 {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入要扫描的目录：");
        String filename = sc.next();
        File file = new File(filename);
        if (!file.isDirectory()) {
            System.out.println("您输⼊的不是目录，退出");
            return;
        }
        System.out.println("请输入关键字：");
        String impName = sc.next();
        traversefile(file, impName);
    }

    private static void traversefile(File file, String impName) throws FileNotFoundException {
        //1.遍历该目录下的文件
        File[] files = file.listFiles();
        //2.判断是否目录是否为空
        if (files == null || files.length == 0) {
            return;
        }
        for (File f : files) {
            //判断是否是目录还是普通文件
            if (f.isDirectory()) {
                traversefile(f, impName);
            } else {
                foudnfile(f, impName);
            }
        }

    }

    private static void foudnfile(File f, String impName) throws FileNotFoundException {
        if(f.getName().contains(impName)) {
            System.out.println("文件名包含关键字"+f.getName());
        }else{
            try(Reader reader= new FileReader(f)) {
                StringBuffer sb = new StringBuffer();
                while(true) {
                    char[] buf = new char[1024];
                    int len= reader.read(buf);
                   if (len == -1) {
                       break;
                   }
                   for(int i=0; i<len; i++) {
                       sb.append(buf[i]);
//                       sb.append(buf, 0, len);
                   }
                   if(sb.toString().contains(impName)) {
                       System.out.println(f.getName());
                   }
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
